package cn.lcl.filter;

import org.apache.log4j.Logger;
import sun.rmi.runtime.Log;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 编码过滤器
 * Created by licho on 2017/8/17 0017.
 */
@WebFilter(value = "/*",initParams = {@WebInitParam(name="encoding" ,value="UTF-8",description = "对post请求进行编码")})
public class EncodingFilter implements Filter {
    private static  final Logger log= Logger.getLogger(EncodingFilter.class);
    private  String encoding;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
            log.info("编码过滤器已启动");
            encoding=filterConfig.getInitParameter("encoding");
            log.info(encoding);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            HttpServletRequest req=(HttpServletRequest)request;
            request.setAttribute("_root",req.getContextPath());
            log.info("root:"+((HttpServletRequest) request).getContextPath());
            request.setCharacterEncoding(encoding);
            chain.doFilter(request,response);
            response.setCharacterEncoding(encoding);
    }

    @Override
    public void destroy() {
        log.debug("编码过滤器销毁");
    }
}
